const db = wx.cloud.database()
const commoditiesCollection = db.collection('commodities')
const cartlistCollection = db.collection('cartlist')
// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAllSelect: false,//默认全选状态为false
    totalPrice: 0,//默认合计为0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    db.collection('cartlist').get().then(res => {
      console.log("成功读取购物车数据", res.data)
      this.setData({
        cartlist: res.data
      })
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 跳转到商品详情页
   */
  navigateToCommodities: function(e) {
    var goodsID = e.currentTarget.dataset.gid;
    var typeID = e.currentTarget.dataset.tid;
    var id = e.currentTarget.dataset.id;

    console.log("即将跳转到第", typeID, "类的第", goodsID, "个商品详情")
    wx.navigateTo({
      url: '../first/commodities/commodities?typeID=' + typeID + '&goodsID=' + goodsID + '&id=' + id,

    })
  },
  /**
   * 结算商品总价
   */
  getTotalPrice() {
    let cartlist = this.data.cartlist;
    let total = 0;
    for (let i = 0; i < cartlist.length; i++) {
      if (cartlist[i].isSelect) {
        total += cartlist[i].num * cartlist[i].optionPrice;
      }
    }
    this.setData({
      cartlist: cartlist,
      totalPrice: total.toFixed(2)
    });
  },
  /**
   * 控制选择商品显示状态事件
   */
  switchSelect(e) {
    const index = e.currentTarget.dataset.index;
    let cartlist = this.data.cartlist;
    const isSelect = cartlist[index].isSelect;
    cartlist[index].isSelect = !isSelect;
    this.setData({
      cartlist: cartlist
    });
    this.getTotalPrice();
    var i, j = 0;
    for (i = 0; i < cartlist.length; i++) {
      if (cartlist[i].isSelect == !isSelect) {
        j++;
      }
    };
    var isAllSelect = this.data.isAllSelect;
    if (j == cartlist.length) {
      this.setData({
        isAllSelect: !isSelect
      });
    } else {
      this.setData({
        isAllSelect: false
      });
    };
  },
  /**
   * 控制购买商品数量在库存范围内
   */
  bindManual: function(e) {
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var stock = e.currentTarget.dataset.stock;
    let cartlist = this.data.cartlist;
    var num = cartlist[index].num;

    if (value <= stock && value >= 1) {
      cartlist[index].num = value;
      this.setData({
        cartlist: cartlist
      });
      cartlistCollection.doc(id).update({
        data: {
          num: value
        },
        success: console.log,
        fail: console.error
      })
    } else {
      cartlist[index].num = num;
      this.setData({
        cartlist: cartlist
      });
      if (value == 0) {
        wx.showToast({
          title: '购买数量不可为0哦！请重新输入',
          icon: 'none',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '购买数量超过库存数啦！请重新输入',
          icon: 'none',
          duration: 2000
        });
      };
    };
    this.getTotalPrice();
  },
  /**
   * 控制商品购物数量"-“
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    let cartlist = this.data.cartlist;
    let num = cartlist[index].num;
    if (num <= 1) {
      wx.showToast({
        title: '不能再减了哦~',
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    num = num - 1;
    cartlist[index].num = num;
    this.setData({
      cartlist: cartlist
    });
    this.getTotalPrice();
    cartlistCollection.doc(id).update({
      data: {
        num: num
      },
      success: console.log,
      fail: console.error
    })
  },
  /**
   * 控制商品购买数量“+”
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    let cartlist = this.data.cartlist;
    let num = cartlist[index].num;
    if (num >= cartlist[index].optionStock) {
      wx.showToast({
        title: '超过库存量啦~',
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    num = num + 1;
    cartlist[index].num = num;
    this.setData({
      cartlist: cartlist
    });
    this.getTotalPrice();
    cartlistCollection.doc(id).update({
      data: {
        num: num
      },
      success: console.log,
      fail: console.error
    })
  },
  /**
   * 控制购物车商品删除事件
   */
  del(e) {
    const index = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    let cartlist = this.data.cartlist;
    cartlist.splice(index, 1);
    this.setData({
      cartlist: cartlist
    });
    this.getTotalPrice();
    cartlistCollection.doc(id).remove({
      success: console.log,
      fail: console.error
    })
  },
  /**
   * 点击全选商品事件
   */
  allSelect(e) {
    let isAllSelect = this.data.isAllSelect;
    isAllSelect = !isAllSelect;
    let cartlist = this.data.cartlist;
    for (let i = 0; i < cartlist.length; i++) {
      cartlist[i].isSelect = isAllSelect;
    }
    this.setData({
      isAllSelect: isAllSelect,
      cartlist: cartlist
    });
    this.getTotalPrice();
  },
  /**
   * 商品结算
   */
  toBuy() {
    var totalPrice = this.data.totalPrice;
    if (totalPrice > 0) {
      wx.showToast({
        title: '该功能尚未开通~',
        icon: 'loading',
        duration: 3000
      });
    } else {
      wx.showToast({
        title: '您还未选择商品哦！',
        icon: 'none',
        duration: 3000
      });
    }
  }
})